<?php

/**
 * Forecast actions.
 *
 * @package    TMD
 * @subpackage Forecast
 * @author     Thaihosting
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class TMDService {
	public static $MSSQL = "MSSQL";
	public static $MYSQL = "MySQL";
	public static $ORACLE = "Oracle";
	public static $strDatabase = "MSSQL";
	public $strMsg = "";
	public static function OpenTransConn() {
		// Connection string for transactional database
		switch (TMDService::$strDatabase) {
			case TMDService::$MSSQL :
				try {
					$cn = &ADONewConnection ( "odbc_mssql" );
					$strTransConn = "Driver={SQL Server};Server=localhost;Database=TMDWEB_TEST;";
					$cn->SetFetchMode ( ADODB_FETCH_ASSOC );
					$cn->Connect ( $strTransConn, "sa", "theangles" );
				} catch ( Exception $e ) {
					var_dump ( $e );
				}
				break;
			
			case TMDService::$MYSQL :
				$cn = &ADONewConnection ( "mysql" );
				$cn->SetFetchMode ( ADODB_FETCH_ASSOC );
				$cn->Connect ( "Server", "DBUsername", "DBPassword", "DBName" );
				break;
		}
		
		return $cn;
	}
	public static function GetUpdateSQL($rs, $arr) {
		// Oracle has only DATE datatype which also includes both
		// date and time value
		if ($rs->connection->dataProvider == "oci8") {
			$intFieldCount = $rs->FieldCount ();
			
			for($i = 0; $i < $intFieldCount; $i ++) {
				$column [] = $rs->FetchField ( $i );
				if ($column [$i]->type == "DATE") {
					$column [$i]->type = "TIMESTAMP";
				}
			}
		}
		
		$strSql = $rs->connection->GetUpdateSQL ( $rs, $arr );
		
		return $strSql;
	}
	public static function test() {
		$cn = TMDService::OpenTransConn ();
		
		$strTimeBackTo = $cn->DBTimeStamp ( strtotime ( "-38 hour", time () ) );
		switch (TMDService::$strDatabase) {
			
			case TMDService::$MSSQL :
				$strSql = "SELECT TOP 1 * FROM EARTHQUAKE"; // WHERE dtdate <= $strTimeBackTo";
				break;
			case TMDService::$MYSQL :
				$strSql = "";
				break;
		}
		
		try {
			if ($rs = $cn->Execute ( $strSql )) {
				
				while ( ! $rs->EOF ) {
					
					$strTitle = $rs->fields ["STITLE"];
					print "$strTitle";
					
					$rs->MoveNext ();
				}
			} 

			else {
				echo "Cannot connect.";
			}
		} catch ( Exception $e ) {
			var_dump ( $e );
		}
		
		$cn->Close ();
	}
	private static $langIndex = array (
			"th_TH" => "Th",
			"en_EN" => "En" 
	);
	public static function findCurrentAsTime() {
		$currentDate = TMDService::findCurrentDate ();
		list ( $y, $m, $d ) = explode ( "-", $currentDate );
		
		return mktime ( 0, 0, 0, $m, $d, $y );
	}
	
	/**
	 * Alert the message to log.
	 *
	 * @param unknown_type $message        	
	 */
	public static function alert($message) {
		sfContext::getInstance ()->getLogger ()->alert ( $message );
	}
	
	/**
	 * Render i18n with object.
	 *
	 * @param unknown_type $obj        	
	 * @param unknown_type $methodWithoutLang        	
	 * @param unknown_type $culture        	
	 * @return mixed
	 */
	public static function renderI18n($obj, $methodWithoutLang, $culture) {

		$method = $methodWithoutLang . TMDService::$langIndex [$culture];
		
		return call_user_func_array ( array (
				$obj,
				$method 
		), array () );
	}
	
	public static function renderI18nYear($year, $culture) {
		if ($culture == 'th_TH') {
			return $year + 543;
		}
		
		return $year;
	}
	
	/**
	 * Find sunset time with lat, long and default zenith = 2.3333
	 *
	 * @param unknown_type $latitude        	
	 * @param unknown_type $longitude        	
	 */
	public static function sunset($latitude, $longitude) {
		$time = strtotime ( "+1 day", time () );
		$v = date_sunset ( $time, SUNFUNCS_RET_STRING, $latitude, $longitude, 90 + 50 / 60 );
		
		return $v;
	}
	
	/**
	 * Find sunrise time with lat, long and default zenith = 2.3333
	 *
	 * @param unknown_type $latitude        	
	 * @param unknown_type $longitude        	
	 * @return mixed
	 */
	public static function sunrise($latitude, $longitude) {
		$time = strtotime ( "+1 day", time () );
		$v = date_sunrise ( $time, SUNFUNCS_RET_STRING, $latitude, $longitude, 90 + 50 / 60 );
		
		return $v;
	}
	public static function addDate($currentDate, $intervalDay) {
		list ( $Y, $m, $d ) = explode ( '-', $currentDate );
		$end = mktime ( 0, 0, 0, $m, $d + $intervalDay, $Y );
		
		return $end;
	}
	
	/**
	 * Find weekly forecast.
	 *
	 * @param unknown_type $params
	 *        	Available parameter
	 *        	- provinceId -> IPROVINCE_ID for find weekly forecast
	 *        	- limit -> total records for returns, default 3 records
	 * @return array of InputLongStay
	 */
	public static function findWeeklyForecast($params = array()) {
		
		$cn = TMDService::OpenTransConn ();
		
		$currentDate = TMDService::findCurrentDate ();
		
		list ( $y, $m, $d ) = explode ( "-", $currentDate );
		$time = $cn->DBTimeStamp(mktime ( 0, 0, 0, $m, $d, $y ));
		
		$start = TMDService::createDateCondition ( InputLongStayPeer::DTTIME_FORECAST_FROM, $time, ">=" );

		$sql = "SELECT * \nFROM " . InputLongStayPeer::TABLE_NAME . " \nWHERE " . $start;
		$sql .= " AND " . InputLongStayPeer::IPROVINCE_ID . "=" . $params ['provinceId'];
		$sql .= "\nORDER BY " . InputLongStayPeer::DTSAVE_TIME . " DESC";
		$sql .= ", " . InputLongStayPeer::DTTIME_FORECAST_FROM . " ASC";
		
		
		$objects = array();
		TMDService::alert( $sql );
		
		if ($rs = $cn->Execute ( $sql )) {
			$fields = InputLongStayPeer::getFieldNames(BasePeer::TYPE_COLNAME);
			$objects = TMDService::getResultsAsObjects($rs, $fields, "InputLongStay");
			
			foreach ( $objects as $object ) {
				TMDService::alert( $object->getDtsaveTime() );
			}
		}
		
		$cn->Close();
		
		return $objects;
	}
	
	private static function getResultsAsObjects( $resultSet, $fields, $className ) {
		TMDService::alert("getResultsAsObjects::$className");
		$data = array();
		while ( ! $resultSet->EOF ) {
			$cls = new $className();
			$row = array();
			foreach( $fields as $field ) {
				
				$row[] = $resultSet->fields[substr($field, strrpos($field, ".") + 1)];
			}
		
			$cls->hydrate($row);
			$data[] = $cls;
			$resultSet->MoveNext ();
		}
		
		return $data;
	}
	
	/**
	 * i18n function for EN shortdate
	 *
	 * @param unknown_type $strDate        	
	 * @param unknown_type $yearDigit        	
	 */
	public static function toDateEn($strDate, $yearDigit = 2) {
		$strYear = date ( "Y", strtotime ( $strDate ) );
		$strMonth = date ( "n", strtotime ( $strDate ) );
		$strDay = date ( "j", strtotime ( $strDate ) );
		
		// TODO IMplement
	}
	
	/**
	 * i18n function for TH shortdate
	 *
	 * @param unknown_type $strDate        	
	 * @param unknown_type $yearDigit        	
	 */
	public static function toDateTh($strDate, $yearDigit = 2) {
		return toThaiDate ( $strDate, $yearDigit );
	}
	public static function toThaiDate($strDate, $yearDigit = 2) {
		$strYear = date ( "Y", strtotime ( $strDate ) ) + 543;
		$strMonth = date ( "n", strtotime ( $strDate ) );
		$strDay = date ( "j", strtotime ( $strDate ) );
		
		$strMonthCut = Array (
				"",
				"ม.ค.",
				"ก.พ.",
				"มี.ค.",
				"เม.ย.",
				"พ.ค.",
				"มิ.ย.",
				"ก.ค.",
				"ส.ค.",
				"ก.ย.",
				"ต.ค.",
				"พ.ย.",
				"ธ.ค." 
		);
		$strMonthThai = $strMonthCut [$strMonth];
		
		return "$strDay $strMonthThai " . substr ( $strYear, 4 - $yearDigit );
	}
	public static function toThaiFullDate($strDate) {
		$strYear = date ( "Y", strtotime ( $strDate ) ) + 543;
		$strMonth = date ( "n", strtotime ( $strDate ) );
		$strDay = date ( "j", strtotime ( $strDate ) );
		
		$strMonthCut = Array (
				"",
				"มกราคม",
				"กุมพาพันธ์",
				"มีนาคม",
				"เมษายน",
				"พฤษภาคม",
				"มิถุนายน",
				"กรกฎาคม",
				"สิงหาคม",
				"กันยายน",
				"ตุลาคม",
				"พฤศจิกายน",
				"ธันวาคม" 
		);
		$strMonthThai = $strMonthCut [$strMonth];
		
		return "$strDay $strMonthThai $strYear";
	}
	public static function toThaiTime($strDate) {
		$strHour = date ( "H", strtotime ( $strDate ) );
		$strMinute = date ( "i", strtotime ( $strDate ) );
		$strSeconds = date ( "s", strtotime ( $strDate ) );
		
		return "$strHour:$strMinute";
	}
	public static function toThaiFullDatetime($strDate) {
		$time = strtotime ( $strDate );
		
		$strYear = date ( "Y", $time ) + 543;
		$strMonth = date ( "n", $time );
		$strDay = date ( "j", $time );
		$strHour = date ( "H", $time );
		$strMinute = date ( "i", $time );
		$strSeconds = date ( "s", $time );
		
		$strMonthCut = Array (
				"",
				"มกราคม",
				"กุมพาพันธ์",
				"มีนาคม",
				"เมษายน",
				"พฤษภาคม",
				"มิถุนายน",
				"กรกฎาคม",
				"สิงหาคม",
				"กันยายน",
				"ตุลาคม",
				"พฤศจิกายน",
				"ธันวาคม" 
		);
		$strMonthThai = $strMonthCut [$strMonth];
		return "$strDay $strMonthThai $strYear, $strHour:$strMinute";
	}
	
	public static function findCurrentDate() {
		return sfConfig::get ( 'sf_current_date' );
	}
	
	/**
	 *
	 * @param unknown $params        	
	 * @return Ambigous <multitype:, multitype:unknown Ambigous <GeographicRegions, NULL, multitype:> >
	 */
	public static function listGeoRegions($params = array()) {
		if (! isset ( $params ['language'] )) {
			$params ['language'] = 'THAI';
		}
		
		$cn = TMDService::OpenTransConn ();
		$sql =  "SELECT DISTINCT * \n";
		$sql .=	"FROM " . GeographicRegionsPeer::TABLE_NAME . "\n";
		$sql .= "WHERE \n";
		$sql .= GeographicRegionsPeer::IGEOGRAPHIC_REGION . " > 0\n";
		$sql .= "ORDER BY SREGION_NAME_{$params['language']} ASC, " . GeographicRegionsPeer::IGEOGRAPHIC_REGION . " ASC";
		
		$objects = array();
		
		if ($rs = $cn->Execute ( $sql )) {
			$fields = InputLongStayPeer::getFieldNames(BasePeer::TYPE_COLNAME);
			$objects = TMDService::getResultsAsObjects($rs, $fields, "GeographicRegions");
		}
		
		$cn->Close();
		
		return $objects;
	}
	
	public static function findInput4wksForecast($params) {
		$regionId = 1;
		if (isset ( $params ['regionId'] )) {
			$regionId = $params ['regionId'];
		}
		
		$currentDate = TMDService::findCurrentDate ();
		if (isset ( $params ['startDate'] )) {
			$currentDate = $params ['startDate'];	
		}
		
		list ( $Y, $m, $d ) = explode ( '-', $currentDate );
		$start = mktime ( 0, 0, 0, $m, $d, $Y );
		$end = mktime ( 0, 0, 0, $m, $d + 6, $Y );
		
		$startForecast = TMDService::createDbDateCondition ( Input4wksForecastPeer::DTTIME_FORECAST_FROM, $start, "<=" );
		$endForecast = TMDService::createDbDateCondition ( Input4wksForecastPeer::DTTIME_FORECAST_TO, $start, ">=" );
		
		/*
		$c = new Criteria ();
		$c->add ( Input4wksForecastPeer::IGEOGRAPHIC_REGION, $regionId );
		$c->add ( Input4wksForecastPeer::DTTIME_FORECAST_TO, "$startForecast AND $endForecast", Criteria::CUSTOM );
		$c->addDescendingOrderByColumn ( Input4wksForecastPeer::DTSAVE_TIME );
		
		$last = Input4wksForecastPeer::doSelectOne ( $c );*/
		
		
		
		
		return $last;
	}
	
	/**
	 * Find Input for 7 days forecaste by GeoRegion.
	 *
	 * @param unknown_type $params        	
	 * @return Ambigous <Input7dForecastGeoregion, NULL, unknown, multitype:>
	 */
	public static function findInput7dForecastByGeRegion($params) {
		$currentDate = TMDService::findCurrentDate ();
		
		list ( $Y, $m, $d ) = explode ( '-', $currentDate );
		
		$start = mktime ( 0, 0, 0, $m, $d, $Y );
		
		$startForecast = TMDService::createDateCondition ( Input7dForecastGeoregionPeer::DTTIME_FORECAST, $start, "=" );
		$c = new Criteria ();
		$c->add ( Input7dForecastGeoregionPeer::IGEOGRAPHIC_REGION, $params ['regionId'] );
		$c->add ( Input7dForecastGeoregionPeer::DTTIME_FORECAST, $startForecast, Criteria::CUSTOM );
		
		$c->addAscendingOrderByColumn ( Input7dForecastGeoregionPeer::DTSAVE_TIME );
		
		$result = Input7dForecastGeoregionPeer::doSelectOne ( $c );
		
		return $result;
	}
	public static function findLastInputDailyForecastGeoRegionDate() {
		$regionId = 1;
		if (isset ( $params ['regionId'] )) {
			$regionId = $params ['regionId'];
		}
		
		$currentDate = TMDService::findCurrentDate ();
		if (isset ( $params ['startDate'] )) {
			$currentDate = $params ['startDate'];
		}
		
		list ( $Y, $m, $d ) = explode ( '-', $currentDate );
		$start = mktime ( 0, 0, 0, $m, $d, $Y );
		$end = mktime ( 0, 0, 0, $m, $d + 1, $Y );
		
		$startForecast = TMDService::createDateCondition ( InputDailyForecastPeer::DTTIME_FORECAST, $start, ">=" );
		$endForecast = TMDService::createDateCondition ( InputDailyForecastPeer::DTTIME_FORECAST, $end, "<=" );
		
		$c = new Criteria ();
		$c->add ( InputDailyForecastPeer::IGEOGRAPHIC_REGION, $regionId );
		$c->add ( InputDailyForecastPeer::DTTIME_FORECAST, "$startForecast AND $endForecast", Criteria::CUSTOM );
		$c->addDescendingOrderByColumn ( InputDailyForecastPeer::DTTIME_FORECAST );
		
		$last = InputDailyForecastPeer::doSelectOne ( $c );
		if ($last) {
			return $last->getDttimeForecast ();
		}
		
		return null;
	}
	
	/**
	 * Find InputDailyForecastDates by region
	 * Available parameter
	 * - currentDate
	 * - regionId
	 *
	 * @param unknown_type $params        	
	 * @return Ambigous <multitype:, multitype:unknown Ambigous <InputDailyForecast, NULL, multitype:> >
	 */
	public static function findInputDailyForecastGeoRegionDates($params) {
		$regionId = 1;
		if (isset ( $params ['regionId'] )) {
			$regionId = $params ['regionId'];
		}
		
		$currentDate = TMDService::findCurrentDate ();
		if (isset ( $params ['startDate'] )) {
			$currentDate = $params ['startDate'];
		}
		
		list ( $Y, $m, $d ) = explode ( '-', $currentDate );
		$end = mktime ( 0, 0, 0, $m, $d + 1, $Y );
		$start = mktime ( 0, 0, 0, $m, date ( 'd', $end ) - 6, $Y );
		
		$startForecast = TMDService::createDateCondition ( InputDailyForecastPeer::DTTIME_FORECAST, $start, ">=" );
		$endForecast = TMDService::createDateCondition ( InputDailyForecastPeer::DTTIME_FORECAST, $end, "<=" );
		
		$c = new Criteria ();
		$c->add ( InputDailyForecastPeer::IGEOGRAPHIC_REGION, $regionId );
		$c->add ( InputDailyForecastPeer::DTTIME_FORECAST, "$startForecast AND $endForecast", Criteria::CUSTOM );
		$c->addDescendingOrderByColumn ( InputDailyForecastPeer::DTTIME_FORECAST );
		
		$results = InputDailyForecastPeer::doSelect ( $c );
		return $results;
	}
	
	/**
	 * //TODO Implement this after discuss with TMD
	 *
	 * @param unknown_type $totalClould        	
	 */
	public static function getCloudDescription($totalClould) {
		return '';
	}
	
	public static function findGeoRegionById($id) {
		$c = new Criteria ();
		$c->add ( GeographicRegionsPeer::IGEOGRAPHIC_REGION, $id );
		
		return GeographicRegionsPeer::doSelectOne ( $c );
	}
	public static function findInputDailyForecastByGeoReigonAndForecastDateTime($regionId, $dttimeForecast) {
		$forecastTime = str_replace ( array (
				" ",
				":" 
		), "-", $dttimeForecast );
		list ( $Y, $m, $d, $h, $m, $s ) = explode ( '-', $forecastTime );
		
		$start = mktime ( $h, $m, $s, $m, $d, $Y );
		$startForecast = TMDService::createDateCondition ( InputDailyForecastPeer::DTTIME_FORECAST, $start, "=" );
		
		$c = new Criteria ();
		$c->add ( InputDailyForecastPeer::DTTIME_FORECAST, $startForecast, Criteria::CUSTOM );
		$c->add ( InputDailyForecastPeer::IGEOGRAPHIC_REGION, $regionId );
		
		return InputDailyForecastPeer::doSelectOne ( $c );
	}
	public static function findInputDailyForecast($params) {
		$startForecast = TMDService::createDateCondition ( InputDailyForecastPeer::DTTIME_FORECAST, $start, ">=" );
		$endForecast = TMDService::createDateCondition ( InputDailyForecastPeer::DTTIME_FORECAST, $end, "<=" );
		
		$c = new Criteria ();
		$c->addDescendingOrderByColumn ( InputDailyForecastPeer::DTSAVE_TIME );
		$c->setLimit ( 8 );
		$c->setOffset ( 0 );
		
		$results = InputDailyForecastPeer::doSelect ( $c );
		
		return $results;
	}
	
	/**
	 *
	 * @param unknown_type $params        	
	 * @return Input7dForecastProvince
	 */
	public static function findLastForecastInputSevenDaysForecastByProvince($params) {
		$c = new Criteria ();
		$c->add ( Input7dForecastProvincePeer::IPROVINCE_ID, $params ['provinceId'] );
		$c->addDescendingOrderByColumn ( Input7dForecastProvincePeer::DTTIME_FORECAST );
		$c->addDescendingOrderByColumn ( Input7dForecastProvincePeer::DTSAVE_TIME );
		$c->setLimit ( 1 );
		$c->setOffset ( 0 );
		
		return Input7dForecastProvincePeer::doSelectOne ( $c );
	}
	public static function findCurrentForecastInputSevenDaysForecastByProvince($params) {
		$c = new Criteria ();
		$c->add ( Input7dForecastProvincePeer::IPROVINCE_ID, $params ['provinceId'] );
		$c->addDescendingOrderByColumn ( Input7dForecastProvincePeer::DTTIME_FORECAST );
		$c->addDescendingOrderByColumn ( Input7dForecastProvincePeer::DTSAVE_TIME );
		$c->setLimit ( 1 );
		$c->setOffset ( 0 );
		
		return Input7dForecastProvincePeer::doSelectOne ( $c );
	}
	
	/**
	 * Find Input for 7 days forecast by Province.
	 *
	 * @param unknown $provinceId        	
	 * @return Ambigous <multitype:, multitype:unknown Ambigous <Input7dForecastProvince, NULL, multitype:> >
	 */
	public static function findInputSevenDaysForecastByProvince($params) {
		
		if (! isset ( $params ['provinceId'] )) {
			$params ['provinceId'] = 37;
		}
		
		$currentDate = TMDService::findCurrentDate ();
		
		list ( $Y, $m, $d ) = explode ( '-', $currentDate );
		
		$start = mktime ( 0, 0, 0, $m, $d, $Y );
		$end = mktime ( 0, 0, 0, $m, date ( 'd', $start ) + 6, $Y );	
		
		$cn = TMDService::OpenTransConn();
		$startForecast = TMDService::createDbDateCondition ( Input7dForecastProvincePeer::DTTIME_FORECAST, $start, ">=", $cn );
		$endForecast = TMDService::createDbDateCondition ( Input7dForecastProvincePeer::DTTIME_FORECAST, $end, "<=", $cn );
		
		$sql = "SELECT * \n";
		$sql .= "FROM " . Input7dForecastProvincePeer::TABLE_NAME . "\n";
		$sql .= "WHERE\n";
		$sql .= Input7dForecastProvincePeer::IPROVINCE_ID . "=" . $params ['provinceId'] . "\n";
		$sql .= "AND $startForecast AND $endForecast" . "\n";
		$sql .= " ORDER BY " . Input7dForecastProvincePeer::DTTIME_FORECAST . " ASC, " . Input7dForecastProvincePeer::DTSAVE_TIME . " ASC\n";
		TMDService::alert($sql);
		$tmp = array();
		
		if ($rs = $cn->Execute ( $sql )) {
			$fields = Input7dForecastProvincePeer::getFieldNames(BasePeer::TYPE_COLNAME);
			$tmp = TMDService::getResultsAsObjects($rs, $fields, "Input7dForecastProvince");
		}
		
		$cn->Close();
		
// 		$c = new Criteria ();
// 		$c->add ( Input7dForecastProvincePeer::IPROVINCE_ID, $params ['provinceId'] );
// 		$c->add ( Input7dForecastProvincePeer::DTTIME_FORECAST, "$startForecast AND $endForecast", Criteria::CUSTOM );
// 		$c->addAscendingOrderByColumn ( Input7dForecastProvincePeer::DTTIME_FORECAST );
// 		$c->addDescendingOrderByColumn ( Input7dForecastProvincePeer::DTSAVE_TIME );
		
		$results = array ();
		
		foreach ( $tmp as $t ) {
			if (count ( $results ) == 0) {
				$results [] = $t;
			} else {
				
				$compare = $results [count ( $results ) - 1];
				if ($compare->getDttimeForecast () != $t->getDttimeForecast ()) {
					$results [] = $t;
				}
			}
		}
		
		return $results;
	}
	
	/**
	 * List all wethertype
	 */
	public static function findAllWeatherTypes() {
		
		$cn = TMDService::OpenTransConn ();
		$sql =  "SELECT DISTINCT * \n";
		$sql .=	"FROM " . WeatherTypePeer::TABLE_NAME . "\n";
		$sql .= "ORDER BY " . WeatherTypePeer::IWEATHER_TYPE . " ASC";
		
		$objects = array();
		
		if ($rs = $cn->Execute ( $sql )) {
			$fields = WeatherTypePeer::getFieldNames(BasePeer::TYPE_COLNAME);
			$objects = TMDService::getResultsAsObjects($rs, $fields, "WeatherType");
		}
		
		$cn->Close();
		
		return $objects;
	}
	
	
	public static function findProvincesByParams( $params ) {
		$cn = TMDService::OpenTransConn ();
		$sql =  "SELECT DISTINCT * \n";
		$sql .=	"FROM " . ProvincesPeer::TABLE_NAME . "\n";
		$sql .= "WHERE 1=1 \n";
		if( isset( $params['provinceId'] ) ) {
			$sql .= "AND " . ProvincesPeer::IPROVINCE_ID . " = {$params['provinceId']}";
		}
		
		if( isset( $params['regionId'] ) ) {
			$sql .= "AND " . ProvincesPeer::IGEOGRAPHIC_REGION . " = {$params['regionId']}";
		}
		
		//$sql .= "ORDER BY " . WeatherTypePeer::IWEATHER_TYPE . " ASC";
		
		$objects = array();
		
		if ($rs = $cn->Execute ( $sql )) {
			$fields = ProvincesPeer::getFieldNames(BasePeer::TYPE_COLNAME);
			$objects = TMDService::getResultsAsObjects($rs, $fields, "Provinces");
		}
		
		$cn->Close();
		
		return $objects;
	}
	
	public static function findInputSevenDaysForecast($params) {
		$c = new Criteria ();
		$c->addDescendingOrderByColumn ( Input7dForecastGeoregionPeer::DTTIME_FORECAST );
		$c->addAscendingOrderByColumn ( Input7dForecastGeoregionPeer::IGEOGRAPHIC_REGION );
		$c->setLimit ( 8 );
		$c->setOffset ( 0 );
		
		$results = Input7dForecastGeoregionPeer::doSelect ( $c );
		
		return $results;
	}
	public static function findInputThreeMonthForecast($params) {
		$c = new Criteria ();
		$c->addDescendingOrderByColumn ( Input3monthsForecastPeer::DTTIME_FORECAST );
		// $c->addAscendingOrderByColumn( Input3monthsForecastPeer:: );
		$c->setLimit ( 8 );
		$c->setOffset ( 0 );
		
		$results = Input3monthsForecastPeer::doSelect ( $c );
		
		return $results;
	}
	
	// TODO Implement
	public static function findInputWeeklySummaryForecast($params) {
		$c = new Criteria ();
		$c->addDescendingOrderByColumn ( InputDailyForecastPeer::DTSAVE_TIME );
		$c->setLimit ( 8 );
		$c->setOffset ( 0 );
		
		$results = InputDailyForecastPeer::doSelect ( $c );
		
		return $results;
	}
	
	/**
	 *
	 * @param unknown_type $params        	
	 * @return GeographicRegions
	 */
	public static function findAllGeographicRegions($params) {
		$c = new Criteria ();
		$c->setDistinct ();
		return GeographicRegionsPeer::doSelect ( $c );
	}
	public static function findLastWeatherProvince($params) {
		// HELLO
		$currentDate = TMDService::findCurrentDate ();
		
		list ( $Y, $m, $d ) = explode ( '-', $currentDate );
		
		$start = mktime ( 0, 0, 0, $m, $d, $Y );
		$end = mktime ( 0, 0, 0, $m, date ( 'd', $start ) + 1, $Y );
		
		$startForecast = TMDService::createDateCondition ( Input3hourPeer::DTTIME, $start, ">=" );
		$endForecast = TMDService::createDateCondition ( Input3hourPeer::DTTIME, $end, "<=" );
		
		$c = new Criteria ();
		$c->add ( Input3hourPeer::ISTATION_ID, $params ['stationId'] );
		// $c->add( Input3hourPeer::DTTIME, "$startForecast AND $endForecast", Criteria::CUSTOM );
		$c->addDescendingOrderByColumn ( Input3hourPeer::DTTIME );
		
		return Input3hourPeer::doSelectOne ( $c );
	}
	
	/**
	 * Find station by provinceId
	 *
	 * @param unknown_type $params        	
	 */
	public static function findStationsByProince($params) {
		$c = new Criteria ();
		$c->addJoin ( ProvincesPeer::SNAME_THAI, StationsPeer::SPROVINCE );
		$c->add ( StationsPeer::BTREPORT_3HOUR, 1 );
		$c->add ( StationsPeer::BTACTIVE, 1 );
		$c->add ( ProvincesPeer::IPROVINCE_ID, $params ['provinceId'] );
		
		return StationsPeer::doSelect ( $c );
	}
	
	/**
	 *
	 * @param unknown_type $params
	 *        	Available params
	 *        	- announceTypeId
	 *        	- limit
	 *        	- offset
	 */
	public static function findLastNews($params) {
		$currentDate = TMDService::findCurrentDate ();
		
// 		$c = new Criteria ();
// 		$c->add ( AnnouncePeer::IANNOUNCE_TYPE, $params ['announceTypeId'] );
// 		$c->addDescendingOrderByColumn ( AnnouncePeer::DTTIME_START );
		
		
		$cn = TMDService::OpenTransConn();
		$limit = 4;
		if( isset( $params['limit'] ) ) {
			$limit = $params['limit'];
		}
		
		$sql = "SELECT TOP $limit * FROM " . AnnouncePeer::TABLE_NAME . " WHERE " . AnnouncePeer::IANNOUNCE_TYPE . "=" . $params['announceTypeId'];
		$sql .= " ORDER BY " . AnnouncePeer::DTTIME_START . " DESC";
		$objects = array();
		
		if ($rs = $cn->Execute ( $sql )) {
			$fields = AnnouncePeer::getFieldNames(BasePeer::TYPE_COLNAME);
			$objects = TMDService::getResultsAsObjects($rs, $fields, "Announce");
		}
		
		$cn->Close();
		
		return $objects;
		
		/*
		$limit = 4;
		if (isset ( $params ['limit'] )) {
			$limit = $params ['limit'];
		}
		
		$c->setLimit ( $limit );
		
		$offset = 0;
		if (isset ( $params ['offset'] )) {
			$offset = $params ['offset'];
		}
		
		$c->setOffset ( $offset );
		
		return AnnouncePeer::doSelect ( $c );
		*/
		
		
	}
	
	/**
	 * Find the last EarthQuake
	 *
	 * @param unknown_type $params        	
	 */
	public static function findLastEarthQuake($params = array()) {
		$params ['limit'] = 1;
		$params ['offset'] = 0;
		$earthQuake = null;
		$earthQuakes = TMDService::findEarthQuakes ( $params );
		if ($earthQuakes && count ( $earthQuakes ) > 0) {
			$earthQuake = $earthQuakes [0];
		}
		
		return $earthQuake;
	}
	
	/**
	 * Find earthquake with params
	 *
	 * @param unknown_type $params        	
	 */
	public static function findEarthQuakes($params = array()) {
		$c = new Criteria ();
		
		if (isset ( $params ['startDate'] ) && isset ( $params ['endDate'] )) {
			
			list ( $Y, $m, $d ) = explode ( '-', $params ['startDate'] );
			$start = mktime ( 0, 0, 0, $m, $d, $Y );
			
			list ( $Y, $m, $d ) = explode ( '-', $params ['endDate'] );
			$end = mktime ( 0, 0, 0, $m, $d, $Y );
			
			$e = TMDService::createDateCondition ( EarthquakePeer::DTTIME, $start, "<=" );
			$s = TMDService::createDateCondition ( EarthquakePeer::DTTIME, $end, ">=" );
			
			$c->add ( EarthquakePeer::DTTIME, "$s AND $e", Criteria::CUSTOM );
		}
		
		$c->addDescendingOrderByColumn ( EarthquakePeer::DTTIME );
		
		$limit = 15;
		if (isset ( $params ['limit'] )) {
			$limit = $params ['limit'];
		}
		
		$c->setLimit ( $limit );
		
		$offset = 0;
		if (isset ( $params ['offset'] )) {
			$offset = $params ['offset'];
		}
		
		$c->setOffset ( $offset );
		
		return EarthquakePeer::doSelect ( $c );
	}
	
	/**
	 * Create datetime condition for SQLServer
	 *
	 * @param string $field        	
	 * @param string $date        	
	 * @param string $condition        	
	 * @return string
	 */
	private static function createDateCondition($field, $date, $condition) {
		//return "$field $condition CONVERT(DATE,'" . date ( 'Y-m-d H:i:s', $date ) . "',102)";
		
		//$strTimeBackTo	= $cn->DBTimeStamp(strtotime("-38 hour",time()));
		
		return "$field $condition $date";
	}
	
	private static function createDbDateCondition( $field, $date, $condition, $cn ) {
		TMDService::alert($date);
		return "$field $condition {$cn->DBTimeStamp( $date )}";
	}
		
	/**
	 * Add limit size for sqlserver from array parameter.
	 *
	 * @param Criteria $c        	
	 * @param unknown_type $params        	
	 */
	private static function attachCriteriaPageSize(Criteria $c, $params) {
		if (isset ( $params ['limit'] )) {
			$c->setLimit ( $params ['limit'] );
		}
		
		if (isset ( $params ['offset'] )) {
			$c->setOffset ( $params ['offset'] );
		}
	}
}

